package com.liyao.windowtest4.controller;

import com.liyao.windowtest4.Utils.ReadTxt;
import com.liyao.windowtest4.Utils.SocketClientUtil;
import com.liyao.windowtest4.controller.mainController;
import com.liyao.windowtest4.pojo.DataRow;
import com.liyao.windowtest4.service.impl.loginServiceImpl;
import com.liyao.windowtest4.service.loginService;
import javafx.application.Platform;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: windowtest4
 * @description:
 * @author: liu yan
 * @create: 2024-11-01 15:46
 */

@Controller
@Component
public class WrenchTask {
//    private final String wrenchId;
    private String wrenchName;

    private String serverAddress;



    public String getServerAddress() {
        return serverAddress;
    }

    private int serverPort;
    private final AtomicBoolean isRunning = new AtomicBoolean(false);
    private ExecutorService executor = Executors.newSingleThreadExecutor();

    private static final int RECONNECT_DELAY_MS = 5000; // 5秒

    private boolean ControlCycle=true;

    private String wrenchSpan;

    private mainController mc;

    // 用于存储每把扳手的连接状态，这里假设扳手ID是字符串类型
    private final ConcurrentHashMap<String, Boolean> wrenchConnectionStates = new ConcurrentHashMap<>();

    // 用于存储每把扳手对应的任务执行线程，方便后续管理
    private final ConcurrentHashMap<String, Thread> wrenchThreads = new ConcurrentHashMap<>();

    // 为每把扳手添加一个消息队列，用于接收重启任务的通知
    private final ConcurrentHashMap<String, BlockingQueue<String>> wrenchRestartQueues = new ConcurrentHashMap<>();

    // 使用CopyOnWriteArrayList替代ArrayList来存储已连接设备ID
    private CopyOnWriteArrayList<String> connectedCountList = new CopyOnWriteArrayList<>();

    // 使用AtomicInteger替代普通整数来记录已连接设备的数量
    private volatile AtomicInteger connectedCount=new AtomicInteger(0);
    private final ReentrantLock countUpdateLock = new ReentrantLock();

    // 用于标记每个wrenId对应的任务是否应该停止，新增的成员变量
    private final ConcurrentHashMap<String, AtomicBoolean> stopFlags = new ConcurrentHashMap<>();

    private boolean returnState;

    private ReadTxt rt;

    private String configDirPath = System.getProperty("user.dir") + File.separator + "config" + File.separator;


    @Resource
    loginService service;



    public void WrenchTaskInit(String wrenchName, String serverAddress, int serverPort, mainController mc) {
//        this.wrenchId = wrenchId;
        this.wrenchName = wrenchName;
//        this.label = label;
        this.serverAddress = serverAddress;
        this.serverPort = serverPort;
//        this.totalConnectedLabel=totalConnectedLabel;
        this.mc=mc;
    }


    // 初始化扳手相关的消息队列和连接状态等信息
    public void initializeWrenchInfo(List<String> wrenchIds) {
        for (String wrenchId : wrenchIds) {
            System.out.println(wrenchId+":pppp");
            this.wrenchConnectionStates.put(wrenchId, false);
            System.out.println("jieguo:"+wrenchConnectionStates.get(wrenchId));
            wrenchRestartQueues.put(wrenchId, new LinkedBlockingQueue<>());
            stopFlags.put(wrenchId, new AtomicBoolean(false));
        }
    }

    // 启动所有扳手的任务执行线程
    public void startAllWrenchTasks(List<String> wrenchIds) {
        for (String wrenchId : wrenchIds) {
            System.out.println("扳手："+wrenchId);
            Boolean connectionStatus = wrenchConnectionStates.get(wrenchId);
            if(connectionStatus!= null){
                System.out.println("www:"+wrenchId);
                if (!wrenchConnectionStates.get(wrenchId)) {
                    System.out.println("bangshou3:"+wrenchId);
                    Thread thread = new Thread(() -> start(wrenchId));
                    wrenchThreads.put(wrenchId, thread);

                    // 检查线程是否已经启动过
                    if (thread.isAlive()) {
                        System.err.println("线程 " + wrenchId + " 已经启动过，不能再次启动");
                        return;
                    }

                    thread.start();
                    wrenchConnectionStates.put(wrenchId, true);

                    // 添加延迟操作，以便有足够时间观察线程启动效果
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    // 可以在这里添加一些检查线程是否已经启动成功的操作，比如检查wrenchThreads.get(wrenchId)是否不为null且处于运行状态
                    if (wrenchThreads.get(wrenchId)!= null && wrenchThreads.get(wrenchId).isAlive()) {
                        System.out.println("线程 " + wrenchId + " 已成功启动");
                    } else {
                        System.out.println("线程 " + wrenchId + " 启动失败");
                    }
                }else{
                    System.out.println("扳手2："+wrenchId);
                }
            }else {
                System.err.println("警告：未找到 " + wrenchId + " 的连接状态信息，可能键不存在或初始化有误。");
                // 可以根据具体情况决定是否设置一个默认的连接状态值，比如设置为 false
                wrenchConnectionStates.put(wrenchId, false);
                // 如果设置了默认值，这里可以继续执行后续的启动线程等操作，也可以根据业务需求决定是否跳过本次启动
            }
            System.out.println(wrenchId+":oooooo");

        }
    }

    // 发送重启任务通知到指定扳手的消息队列
    public void sendRestartTaskNotification(String wrenchId) {
        BlockingQueue<String> restartQueue = wrenchRestartQueues.get(wrenchId);
        try {
            restartQueue.put("RESTART_TASK");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("发送重启任务通知时被中断: " + e);
        }
    }

    public void start(String wrenchId) {
        if (isRunning.compareAndSet(false, true)) {
            executor.submit(() -> {
                while (isRunning.get()) {
                    System.out.println(wrenchId+":执行连接，IP地址："+serverAddress+",端口号："+serverPort);
//                    InetSocketAddress socketAddress = new InetSocketAddress(serverAddress, serverPort);
//                    Socket socket = new Socket();
//                    SocketClientUtil scu=new SocketClientUtil(serverAddress,serverPort);
//                    try{
//                        socket.connect(socketAddress, 5000);
                        try (//Socket socket = new Socket(serverAddress, serverPort);
                             SocketClientUtil scu=new SocketClientUtil(serverAddress,serverPort)) {
                            scu.connect();
                            // 发送信息到服务器
                            String messageToSend = "RSVI;01;"+wrenchId+";01;\r\n";
                            scu.sendMessage(messageToSend);

                            // 接收服务器的回信
                            String response = scu.receiveMessage();
                            System.out.println("resp0"+response);
                            wrenchSpan=Double.parseDouble(response.split(";")[8])/10+"";
                            Platform.runLater(() -> {
                                if (response != null) {
                                    if(response.split(";")[2].equals(wrenchId)){
                                        returnState=true;
                                        Platform.runLater(() -> mc.setLabelStyle(wrenchId,"-fx-text-fill: blue"));

                                        Platform.runLater(() -> mc.setOnlineSum(wrenchId,true));

                                    }
                                    System.out.println(wrenchName + ": 收到回信: " + response);
                                } else {
                                    System.out.println(wrenchName + ": 连接关闭，未收到回信");
                                }
                            });

//                            synchronized (this){
                                rt=new ReadTxt(wrenchId);
//                            }
                            String routineName= rt.getRoutineName();
                            if(rt.isLoop()){
                                while (ControlCycle){
                                    System.out.println("循环开始：");
//                                    socket.close();

                                    //循环发送list中的单项任务
                                    int routineSize=rt.getJobContent().size();
                                    int i=0;
                                    System.out.println("程序的大小："+routineSize);
                                    if(rt.getJobContent().size()>1){
                                        //去查询这把扳手最后一次拧紧任务的编号是多少
                                        int maxScrewID=getScrewID(wrenchId);
                                        if(maxScrewID<routineSize){
                                            i=getScrewID(wrenchId);
                                        }
                                    }
                                    while (i<rt.getJobContent().size()){

//                                        scu.connect();
                                        System.out.println("i的大小："+i);
                                        JSONObject js=JSONObject.fromObject(rt.getJobContent().get(i));
                                        //下发任务给扳手
                                        String mes="RSSP;02;"+wrenchId+";01;1;"+rt.getRoutineName()+";0;2;"+wrenchSpan+";"+js.getString("TorqueMin")+";"+js.getString("TorqueTarget")+";"+js.getString("TorqueMax")+";"+js.getString("StartAngle")+";"+js.getString("AngleMin")+";"+js.getString("AngleTarget")+";"+js.getString("AngleMax")+";1;1;0;1;0;0;\r\n";
//                                    scu.sendMessage("RSSP;02;"+wrenchId+";01;1;"+rt.getRoutineName()+";0;2;"+wrenchSpan+";34;35;36;0;0;0;0;1;1;0;1;0;0;\r\n");
                                        scu.sendMessage(mes);
                                        String resp= null;
                                        resp = scu.receiveMessage();

                                        System.out.println("Server response1: " + resp);
                                        if (resp != null) {
                                            if(resp.split(";")[4].equals("0")){
                                                System.out.println("下发程序成功："+routineName);
                                                //下发成功
//                                                scu.close();
                                                boolean a=true;
                                                while (a){
//                                                    System.out.println("a==true;开始循环");
                                                    String resp2 = null;
//                                                    scu.connect();
                                                    scu.sendMessage("RSTS;1;"+wrenchId+";1;\r\n");
                                                    // 从服务器接收消息
                                                    resp2 = scu.receiveMessage();

//                                                    System.out.println("Server response2: " + resp2);
                                                    if(resp2!=null && resp2.split(";")[7].equals("1")){
                                                        System.out.println("有数据要上传了");
//                                                        scu.close();
//                                                        scu.connect();
                                                        scu.sendMessage("RSTD;01;"+wrenchId+";01;\r\n");
                                                        // 从服务器接收消息
                                                        String resp3 = null;
                                                        resp3 = scu.receiveMessage();
                                                        System.out.println("Server response3: " + resp3);
                                                        if(resp3!=null){
                                                            String [] resp3Arr=resp3.split(";");
//                                                            System.out.println("ww333:"+resp3Arr[2]+","+resp3Arr[11]+","+resp3Arr[12]);
//                                                            System.out.println("ww334:"+wrenchId+","+resp3Arr[11]+","+routineName);

                                                            if(resp3Arr[2].equals(wrenchId) && resp3Arr[11].equals("1") && resp3Arr[12].equals(routineName)){
                                                                //判断扭矩是否合格，不合格重新发送的逻辑
                                                                System.out.println("ww:"+resp3.split(";")[2]+","+resp3.split(";")[11]+","+resp3.split(";")[12]);
                                                                double low = Double.parseDouble(resp3Arr[13]);
                                                                double target = Double.parseDouble(resp3Arr[14]);
                                                                double high = Double.parseDouble(resp3Arr[15]);
                                                                double real = Double.parseDouble(resp3Arr[22]);
                                                                String outcomeCol="";
                                                                if(real<low || real>high){
                                                                    outcomeCol="NG";
                                                                }else{
                                                                    outcomeCol="OK";
                                                                }
//                                                                if(real<low || real>high){//实际扭矩低于扭矩下限，不保存数据
//                                                                    System.out.println("real:"+real+";low:"+low);
//                                                                    System.out.println("real:"+real+";high:"+high);
//                                                                    a=false;
//                                                                    System.out.println("未在扭矩上、下限范围，放弃此数据，再次下发此任务：继续循环");
//                                                                }else{
                                                                    //写入data中
                                                                    WriteTxt(wrenchName,resp3.split(";")[22],i+1,target,low,high,outcomeCol);
                                                                    a=false;//跳出循环
                                                                    System.out.println("跳出循环");
                                                                    i++;
//                                                                }
                                                            }else{
                                                                a=false;
                                                                System.out.println("继续循环");
                                                            }
                                                        }
//                                                        scu.close();
                                                    }else{
//                                                        System.out.println("没有数据要上传的");
//                                                        scu.close();
                                                        a=true;
                                                        Thread.sleep(500);
                                                    }
                                                }
//                                                i++;
                                            }else if(resp.split(";")[4].equals("6")){
                                                System.out.println("扳手正忙");
                                                scu.sendMessage("RSTD;01;"+wrenchId+";01;\r\n");
                                                // 从服务器接收消息
                                                String resp3 = null;
                                                try {
                                                    resp3 = scu.receiveMessage();
                                                } catch (IOException e) {
                                                    throw new RuntimeException(e);
                                                }
                                                System.out.println("Server response3-1: " + resp3);

                                                //验证PsetID鱼PsetName是否对应，如果不对应不跳出循环，接着询问
                                                if(resp3.split(";")[2].equals(wrenchId) && resp3.split(";")[11].equals("1") && resp3.split(";")[12].equals(routineName)){
                                                    //判断扭矩是否合格，不合格重新发送的逻辑
                                                    System.out.println(resp3.split(";")[2]+","+resp3.split(";")[11]+","+resp3.split(";")[12]);
                                                    //写入data中
                                                    try {
                                                        System.out.println("ww:"+resp3.split(";")[2]+","+resp3.split(";")[11]+","+resp3.split(";")[12]);
                                                        String [] resp3Arr=resp3.split(";");
                                                        double low = Double.parseDouble(resp3Arr[13]);
                                                        double target = Double.parseDouble(resp3Arr[14]);
                                                        double high = Double.parseDouble(resp3Arr[15]);
                                                        double real = Double.parseDouble(resp3Arr[22]);
                                                        String outcomeCol="";
                                                        if(real<low || real>high){
                                                            outcomeCol="NG";
                                                        }else{
                                                            outcomeCol="OK";
                                                        }
                                                        WriteTxt(wrenchName,resp3.split(";")[22],i+1,target,low,high,outcomeCol);
                                                    } catch (IOException e) {
                                                        throw new RuntimeException(e);
                                                    }
//                                                    a=false;//跳出循环
                                                    System.out.println("跳出循环");

                                                }else{
                                                    //a=true;
                                                    System.out.println("继续循环(正忙)");
                                                    System.out.println(resp3.split(";")[2]+","+resp3.split(";")[11]+","+resp3.split(";")[12]);
                                                }
//                                                scu.close();
                                            }else if(resp.split(";")[4].equals("2")){
                                                System.out.println("无效的扭矩参数");
                                            }
                                        } else{
                                            System.out.println("扳手无响应");
//                                            scu.close();
                                        }
                                    }
                                }
                            }else{
                                System.out.println(wrenchId+":此扳手无任务");
                                Platform.runLater(() -> mc.setLabelStyle(wrenchId,"-fx-text-fill: green"));
                            }
                            // 模拟每隔5秒重新连接（实际上，这里应该是一个持续连接，但为了演示，我们不断重新连接）
                            Thread.sleep(RECONNECT_DELAY_MS);
                        } catch (IOException | InterruptedException e) {
                            returnState=false;
                            System.err.println(wrenchId+":"+e);
                            Platform.runLater(() -> mc.setLabelStyle(wrenchId,"-fx-text-fill: red"));

                            Platform.runLater(() -> mc.setOnlineSum(wrenchId,false));
                            try {
                                // 等待一段时间后重试连接
                                Thread.sleep(RECONNECT_DELAY_MS);
                            } catch (InterruptedException ie) {
                                Thread.currentThread().interrupt();
                                System.err.println("线程中断异常：" + e);
                            }
                        }
//                    } catch (Exception e){
//                        System.out.println(connectedCount.get()+"-==-==-==-=");
//                        returnState=false;
//                        System.err.println(wrenchId+":::"+e);
//                        Platform.runLater(() -> mc.setLabelStyle(wrenchId,"-fx-text-fill: red"));
//
//                        Platform.runLater(() -> mc.setOnlineSum(wrenchId,false));
//
//                        try {
//                            // 等待一段时间后重试连接
//                            Thread.sleep(RECONNECT_DELAY_MS);
//                        } catch (InterruptedException ie) {
//                            Thread.currentThread().interrupt();
//                            System.err.println("线程中断异常：" + e);
//                        }
//                    }
                }
            });
        }
    }

    public void stop(String wrenId) {
        AtomicBoolean stopFlag = stopFlags.get(wrenId);
        if (stopFlag!= null) {
            stopFlag.set(true);
        }
    }

    public void stop() {
        isRunning.set(false);
        executor.shutdownNow();
    }

    // 一个静态方法，用于获取当前已连接的数量


    public void WriteTxt(String wrenchName,String torqueValue,int screwID,double targetTorque,double minTorque,double maxTorque,String outcomeCol) throws IOException {

        System.out.println("到写入的方法了");

        String configDirPath = System.getProperty("user.dir") + File.separator + "config" + File.separator;

        JSONArray arr=new JSONArray();
        int rows=0;
        try (BufferedReader br = new BufferedReader(new FileReader(configDirPath+"data.txt"))) {

            if(br==null){
                System.err.println("未找到系统文件：data.txt");
            }

            SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");
            String line;

            while ((line = br.readLine()) != null) {
                if(line.contains(sdf1.format(new Date())) && line.contains(wrenchName)){
                    arr.add(JSONObject.fromObject(line));
                }
                rows++;
            }
            System.out.println("arr:"+arr);
            System.out.println("arr.size():"+arr.size());
        } catch (IOException e) {
            System.err.println("读取data.txt失败");
            e.printStackTrace();
        }

        int totality=arr.size()+1;
//        for (int i = 0; i < arr.size(); i++) {
//            JSONObject js=JSONObject.fromObject(arr.get(i));
//            if(js.getString("timestamp").contains(sdf1.format(new Date())) && js.getString("wrenchName").contains(wrenchName)){
//                totality++;
//            }
//        }


        SimpleDateFormat sdfDate=new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdfTime=new SimpleDateFormat("HH:mm:ss");
//        String filePath = "src/main/resources/data.txt";
        String number="CG"+(rows+1);
        DataRow newData = new DataRow(number, wrenchName, mc.getBarCodeInput(), screwID+"",targetTorque+"",minTorque+"",maxTorque+"",torqueValue+" N.m", outcomeCol,sdfDate.format(new Date()),sdfTime.format(new Date()), totality);

        Platform.runLater(() -> mc.addDataEvent(newData));

        // 将URL转换为文件路径格式（不同操作系统可能需要不同处理）
        String filePath = configDirPath+"data.txt";
        try (FileOutputStream fos=new FileOutputStream(filePath,true);
             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"))) { // true 表示追加模式
//        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) { // true 表示追加模式
            // 遍历数据列表并写入文件
            System.out.println(newData.toString()+"newData");
            writer.write(newData.toString()); // 假设DataRow有一个合适的toString()方法，该方法返回包含所有字段的字符串表示
            writer.newLine(); // 每行数据后换行
            System.out.println("写入文件成功");
        } catch (IOException e) {
            e.printStackTrace(); // 打印错误堆栈信息到控制台（通常不推荐在生产环境中这样做）
            // 在实际应用中，您应该使用更用户友好的错误处理方式，比如显示一个错误消息对话框
        }
        //写入数据库
        System.out.println("是否需要写入数据库 :"+mc.getDbstate());
        if(mc.getDbstate().equals("true")){
            try{
                mc.service.insertDB(newData,mc.getDbTable());
            }catch (Exception e){
                System.err.println("数据库错误："+e);
            }
        }else{
            System.out.println("不用写入数据库。。。");
        }
    }
    public void WriteTxt2(String wrenchName,String torqueValue,mainController mc) throws IOException {

        System.out.println("到写入的方法了");

        String configDirPath = System.getProperty("user.dir") + File.separator + "config" + File.separator;

        JSONArray arr=new JSONArray();
        int rows=0;
        try (BufferedReader br = new BufferedReader(new FileReader(configDirPath+"data.txt"))) {

            if(br==null){
                System.err.println("未找到系统文件：data.txt");
            }

            SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");
            String line;

            while ((line = br.readLine()) != null) {
                if(line.contains(sdf1.format(new Date())) && line.contains(wrenchName)){
                    arr.add(JSONObject.fromObject(line));
                }
                rows++;
            }
            System.out.println("arr:"+arr);
            System.out.println("arr.size():"+arr.size());
        } catch (IOException e) {
            System.err.println("读取data.txt失败");
            e.printStackTrace();
        }

        int totality=arr.size()+1;
//        for (int i = 0; i < arr.size(); i++) {
//            JSONObject js=JSONObject.fromObject(arr.get(i));
//            if(js.getString("timestamp").contains(sdf1.format(new Date())) && js.getString("wrenchName").contains(wrenchName)){
//                totality++;
//            }
//        }


        SimpleDateFormat sdfDate=new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdfTime=new SimpleDateFormat("HH:mm:ss");
//        String filePath = "src/main/resources/data.txt";
        String number="CG"+(rows+1);
        System.out.println("number:"+number);
        String barCode=mc.getBarCodeInput();
        System.out.println("条码："+mc.getBarCodeInput());
        /**
         * barCode //条码
         * screwID //螺栓编号
         * targetTorque //目标扭矩
         * minTorque //扭矩下限
         * maxTorque //扭矩上限
         * outcomeCol // 判定
         * */
        DataRow newData = new DataRow(number, wrenchName,barCode, 1+"", 2.1+"", 1.11+"",3.1+"", torqueValue+" N.m", "合格", sdfDate.format(new Date()),sdfTime.format(new Date()), totality);

        Platform.runLater(() -> mc.addDataEvent(newData));
        // 将数据（包括新添加的数据）写入文件

//        URL url = getClass().getClassLoader().getResource("data.txt");
//        if (url == null) {
//            throw new IOException("无法找到data.txt文件");
//        }
//        String getPath=url.toString();
//        if(getPath.contains("file:/")){
//            getPath=getPath.replace("file:/","");
//        }
//        if(getPath.contains("jar:")){
//            getPath=getPath.replace("jar:","");
//        }

        // 将URL转换为文件路径格式（不同操作系统可能需要不同处理）
        String filePath = configDirPath+"data.txt";
        System.out.println("filePath:"+filePath);
        try (FileOutputStream fos=new FileOutputStream(filePath,true);
             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"))) { // true 表示追加模式
//        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) { // true 表示追加模式
            // 遍历数据列表并写入文件
            System.out.println(newData.toString()+"newData");
            writer.write(newData.toString()); // 假设DataRow有一个合适的toString()方法，该方法返回包含所有字段的字符串表示
            writer.newLine(); // 每行数据后换行
            System.out.println("写入文件成功");
        } catch (IOException e) {
            e.printStackTrace(); // 打印错误堆栈信息到控制台（通常不推荐在生产环境中这样做）
            // 在实际应用中，您应该使用更用户友好的错误处理方式，比如显示一个错误消息对话框
        }
        //写入数据库
        System.out.println("是否需要写入数据库 :"+mc.getDbstate());
        if(mc.getDbstate().equals("true")){
            try{
                mc.service.insertDB(newData,mc.getDbTable());
            }catch (Exception e){
                System.err.println("数据库错误："+e);
            }
        }else{
            System.out.println("不用写入数据库。。。");
        }
    }

    public boolean isReturnState() {
        return returnState;
    }

    public int getScrewID(String wrenchName){
        List<JSONObject> dataList = new ArrayList<>();
        String filePath=configDirPath + "data.txt";
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine())!= null) {
                if (line.length() > 0) {
                    JSONObject js = JSONObject.fromObject(line);
                    dataList.add(js);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        JSONObject lastObj = dataList.stream()
                .filter(obj -> obj.getString("wrenchName").equals(wrenchName))
                .max(Comparator.comparing((JSONObject obj) -> {
                    try {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date date = sdf.parse(obj.getString("date") + " " + obj.getString("time"));
                        return date;
                    } catch (Exception e) {
                        e.printStackTrace();
                        return null;
                    }
                })).orElse(null);

        if (lastObj!= null) {

            return Integer.parseInt(lastObj.getString("screwID"));
        }

        return 0;
    }
}
